package com.mtr.middleware;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mtr.sdk.ExecuteResult;
import com.mtr.sdk.IMiddleware;
import com.mtr.sdk.Parameter;

import java.util.HashMap;
import java.util.List;
import java.sql.*;
import java.util.Map;

public class MysqlMiddleWare implements IMiddleware {
    public static void main(String[] args) {

    }
    public ExecuteResult Execute(List<Parameter> parameters) {
        //dburl,uid,pwd,sql
        var parameterMaps = new HashMap<String, String>();
        for (var p : parameters) {
            parameterMaps.put(p.getName(), p.getValue());
        }
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            conn = DriverManager.getConnection(parameterMaps.get("dburl"), parameterMaps.get("uid"), parameterMaps.get("pwd"));
            stmt = conn.createStatement();
            String sql = parameterMaps.get("sql");
            rs = stmt.executeQuery(sql);

            //通过ResultSetMetaData获取字段
            ResultSetMetaData metaData = rs.getMetaData();
            var colCount = metaData.getColumnCount();
            var jsonList = new JSONArray();
            while (rs.next()) {
                var jsonObj = new JSONObject();
                for (var i = 0; i <colCount; i++) {
                    try {
                        //获取字段别名
                        String aliasName = metaData.getColumnLabel(i+1);
                        var value = rs.getObject(aliasName);
                        jsonObj.put(aliasName, value);
                    } catch (Exception ex) {
                        System.out.println(ex);
                    }
                }
                jsonList.add(jsonObj);
            }
            return new ExecuteResult(jsonList);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return new ExecuteResult(e.toString());
        } finally {
            try {
                conn.close();
            } catch (Exception ex) {
            }
            try {
                stmt.close();
            } catch (Exception ex) {
            }
            try {
                rs.close();
            } catch (Exception ex) {
            }
        }
    }
}